package com.it.cloud.modules.oss.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.it.cloud.common.base.Result;
import com.it.cloud.common.exceptions.YYException;
import com.it.cloud.common.utils.PageUtils;
import com.it.cloud.modules.oss.entity.OssResourceEntiry;
import com.it.cloud.modules.oss.service.CloudStorageService;
import com.it.cloud.modules.oss.service.IOssResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 司马缸砸缸了
 * @since 2019-07-12
 */
@Api(value = "OSS控制器", tags = "OSS")
@Slf4j
@RestController
@RequestMapping("/admin/oss")
public class OssResourceController {
    @Autowired
    private IOssResourceService ossResourceService;

    @Autowired
    private CloudStorageService cloudStorageService;


    @ApiOperation(value = "分页查询接口", notes = "条件，分页查询")
    @GetMapping("")
    public Result list(@RequestParam Map<String, Object> params) {
        PageUtils page = ossResourceService.queryPage(params);

        return Result.ok(page);
    }

    @ApiOperation(value = "上传文件接口", notes = "上传文件")
    @PostMapping("/upload")
    public Result uploadCover(MultipartFile file) throws Exception {
        if (file != null && file.isEmpty()) {
            throw new YYException("上传文件不能为空");
        }
        // 上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = cloudStorageService.uploadSuffix(file.getBytes(), suffix);

        // 存储数据库
        OssResourceEntiry resource = new OssResourceEntiry();
        String uuid = IdUtil.randomUUID();
        resource.setId(uuid);
        resource.setUrl(url);
        resource.setName(file.getOriginalFilename());
        resource.setCreateTime(DateUtil.date().toTimestamp());
        ossResourceService.save(resource);

        return Result.ok(uuid);
    }

    @ApiOperation(value = "删除", notes = "删除")
    @PostMapping("/delete")
    public Result delete(@RequestBody String[] ids) {
        log.info("删除资源ids:{}", JSONUtil.toJsonStr(ids));
        ossResourceService.removeByIds(Arrays.asList(ids));

        return Result.ok();
    }

}
